use std::{cell::RefCell, rc::Rc};

use super::Application;

mod proxy;
pub use proxy::*;

#[derive(Clone, Copy)]
pub struct AppRef;
impl types::AppRef for AppRef {
	type Proxy = AppProxy;
	fn exit(&self) {
		// not surport
	}
	fn proxy(&self) -> AppProxy {
		AppProxy()
	}
}

pub struct AppHandle;
impl AppHandle {
	pub fn run(&self) {
		CACHE.with_borrow(|vars| {
			if let Some(rep) = vars.gate.as_ref() {
				rep.on_launch(AppRef)
			}
		});
	}
}

pub struct AppVars {
	gate: Option<Rc<dyn types::AppRep<Application>>>,
}

thread_local! {
	static CACHE:RefCell<AppVars> = RefCell::new(AppVars {
		gate:None,
	});
}
pub(crate) fn init_app(rep: impl types::AppRep<Application>) {
	CACHE.with_borrow_mut(|vars| {
		vars.gate = Some(Rc::new(rep));
	});
}
pub(crate) fn with_app(fun: impl FnOnce(AppRef)) {
	fun(AppRef)
}
